package com.nageoffer.shortlink.project.service.impl;

import com.nageoffer.shortlink.project.service.UrlTitleService;
import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.net.URL;

/**
 * ClassName: UrlTitleServiceImpl
 * Package:
 * Description:  URL接口实现层
 *
 * @Author:xiaohei
 * @Create 2024/6/10 17:27
 * Version 1.0
 */
@Service
public class UrlTitleServiceImpl implements UrlTitleService {

    /**
     * 根据Url获取标题
     *
     * @param url 目标网站地址
     * @return 网站标题
     */
    @SneakyThrows
    @Override
    public String getTitleByUtl(String url) {
        URL targetUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        int responseCode = connection.getResponseCode();
        if(responseCode == HttpURLConnection.HTTP_OK){
            Document document = Jsoup.connect(url).get();
            return document.title();
        }
        return "Error while fetching title ";
    }
}
